﻿using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RuYiAdmin.Net.CommonInfrastructure.Classes;
using RuYiAdmin.Net.CommonInfrastructure.Configurations;
using RuYiAdmin.Net.CommonInfrastructure.Models;
using RuYiAdmin.Net.ServiceLayer.BusinessService.Interface.FrameworkInterface;
using System;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RuYiAdmin.Net.WebApi.RuYiAdminController.FrameworkController
{
    [Route(RuYiGlobalConfig.RouteTemplate)]
    [ApiController]
    public class RuYiAdminCaptchaController : ControllerBase
    {
        #region 属性及其构造函数

        /// <summary>
        /// Lazy.Captcha接口实例
        /// </summary>
        private readonly ICaptcha LazyCaptcha;

        /// <summary>
        /// Redis服务接口实例
        /// </summary>
        private readonly IRedisService RedisService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="LazyCaptcha"></param>
        /// <param name="RedisService"></param>
        public RuYiAdminCaptchaController(ICaptcha LazyCaptcha, IRedisService RedisService)
        {
            this.LazyCaptcha = LazyCaptcha;
            this.RedisService = RedisService;
        }

        #endregion

        #region 获取登录验证码

        /// <summary>
        /// 获取登录验证码
        /// </summary>
        /// <returns>ActionResponseResult</returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult GetCaptcha()
        {
            var captcha = new CaptchaPicture();

            captcha.Id = Guid.NewGuid();
            CaptchaData lazyCaptchaInfo = this.LazyCaptcha.Generate(captcha.Id.ToString());
            captcha.CaptchaValue = "data:image/gif;base64," + lazyCaptchaInfo.Base64;

            this.RedisService.Set(captcha.Id.ToString(), lazyCaptchaInfo.Code, RuYiGlobalConfig.JwtSettings.SaltExpiration);

            var actionResponseResult = ActionResponseResult.Success(captcha);
            return Ok(actionResponseResult);
        }

        #endregion
    }
}
